package com.springcloud.common.web.interceptor;

import com.alibaba.fastjson.JSONObject;
import com.springcloud.common.web.util.AbstractUserContextHolder;
import org.apache.commons.lang.StringUtils;
import org.springframework.web.servlet.HandlerInterceptor;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * <p>  </p>
 *
 * @author mori
 * @since 11/7/2019 4:05 PM
 */
public abstract class AbstractUserInterceptor<T> implements HandlerInterceptor {

    private final static String X_CLIENT_TOKEN_USER = "x-client-token-user";

    private AbstractUserContextHolder<T> abstractUserContextHolder;

    public AbstractUserInterceptor(AbstractUserContextHolder<T> abstractUserContextHolder) {
        this.abstractUserContextHolder = abstractUserContextHolder;
    }

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        String userInfoString = StringUtils.defaultIfBlank(request.getHeader(X_CLIENT_TOKEN_USER), "{}");
        String username = JSONObject.parseObject(userInfoString).getString("user_name");
        T context = getContext(username);
        if (context != null) {
            abstractUserContextHolder.setContext(context);
        }
        return true;
    }

    /**
     * 设置上下文对象
     *
     * @param username
     * @return
     */
    public abstract T getContext(String username);

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler,
                                Exception ex) {
        abstractUserContextHolder.clear();
    }
}
